@echo off
chcp 65001
setlocal enabledelayedexpansion

REM 检查12345端口是否被占用
set PORT=12345
set PID=
for /f "tokens=5" %%a in ('netstat -ano ^| findstr ":%PORT%" ^| findstr "LISTENING"') do (
    set PID=%%a
)

REM 如果找到占用进程则终止
if defined PID (
    echo 端口 %PORT% 被进程 !PID! 占用，正在终止...
    taskkill /F /PID !PID! >nul 2>&1
    timeout /t 3 /nobreak >nul
)

REM 再次检查端口是否释放
set PID=
for /f "tokens=5" %%a in ('netstat -ano ^| findstr ":%PORT%" ^| findstr "LISTENING"') do (
    set PID=%%a
)

if defined PID (
    echo 无法终止占用端口 %PORT% 的进程
    exit /b 1
)

REM 启动Python程序并记录PID
echo 正在启动 main.py...
start python main.py

REM 等待程序启动
timeout /t 2 /nobreak >nul

REM 获取Python进程PID
set PYTHON_PID=
for /f "tokens=2 delims=," %%a in ('wmic process where "name='python.exe' and commandline like '%%main.py%%'" get processid /format:csv ^| findstr "[0-9]"') do (
    set PYTHON_PID=%%a
)

if defined PYTHON_PID (
    echo !PYTHON_PID! > python_pid.txt
    echo main.py 已启动，PID: !PYTHON_PID!
) else (
    echo 无法获取Python进程ID
    exit /b 1
)

endlocal